<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Model;
use Think\Model;

/**
 * 文档基础模型
 */
class LoanModel extends Model{

    /* 用户模型自动完成 */
    protected $_auto = array(

        array('status', 1, self::MODEL_INSERT),
    );

    //更新状态
    public function UpdateStatus($map,$status,$content='',$uid=0){
        $info = M('Loan')->where($map)->field('id,uid,name,day,create_time,money,payable,repayment')->find();
        if(empty($info)) return false;
        if($status==6){
            $url = U('Weixin/Capital/loanview?id='.$info['id'],'',true,'weixin.jcsmkj.cn');
                M('loan')->where("id='{$info['id']}'")->save(['status'=>6,'huankuan_time'=>time()]);//还款
                // $LoanLog =  M('LoanLog');
                // $logData = [
                //     'uid'           => $uid,
                //     'loan_id'       => $info['id'],
                //     'content'       => $content,
                //     'create_time'   => NOW_TIME,
                //     'status'        => 6,
                // ];
                // $LoanLog->add($logData);
                /**还原额度*/
                M('Member')->where("uid=".$info['uid'])->save('used_money',0);
                // M('Member')->where("uid=".$info['uid'])->setDec('used_money',$info['money']);
                //提醒
                $data = [
                    'title'=>'还款成功',
                    'money'=>$info['money'],
                    'type'=>'还款',
                    'status'=>'成功还款',
                    'mydate'=>date('Y-m-d H:i',$info['expire_time']),
                    'date'=>date('Y-m-d H:i'),
                    'remark'=>'您已还款成功，感谢您的使用！',
                ];
                D('Notice')->weixin(5,$info['uid'],$data,$url);
                // $bank=D('BankCard')->where(array('uid='.$info['uid'],'card_number'=>$info['bank_card']))->find();
                // $url='http://sh2.ipyy.com/smsJson.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！您已通过其他方式主动还款，已为您恢复额度，可继续使用，客服热线0771-5717965&sendTime=&extno=';
                // $this->send_post($url);
           return ['status'=>true,'info'=>'操作成功'];
        }elseif($status==5){
            $userinfo = M('Member')->where("uid={$info['uid']}")->field('mobile,quota,used_money')->find();
            $quota    = $userinfo['quota'] - $userinfo['used_money'];
            if($quota<$info['money']){
                return ['status'=>false,'info'=>'该用户额度不足，无法打款'];
            }
            $used_money = $userinfo['used_money'] + $info['money'];
            M('Member')->where("uid={$info['uid']}")->save(['used_money'=>$used_money]);
            $expire_time = strtotime("+{$info['day']} day");
            $data = ['status'=>$status,'loan_time'=>time(),'expire_time'=>$expire_time];
            $data2 = [
              'name'    =>  $info['name'],
              'money'   =>  $info['money'],
              'operate' =>  '借款',
              'status'  =>  '打款成功',
              'date'    =>  date('Y年m月d日 H:i:s'),
            ];
            D('Notice')->weixin(4,$info['uid'],$data2);
            // $date = date('Y年m月d日',$expire_time);
            // $bank=D('BankCard')->where(array('uid='.$info['uid'],'card_number'=>$info['bank_card']))->find();
            // $url='http://sh2.ipyy.com/smsJson.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！您申请的借款已由资金方汇款成功，到账金额'.$info['payable'].'元，合同到期为'.$date.'，合同金额为'.$info['money'].'元，客服热线0771-5717965&sendTime=&extno=';
            // $this->send_post($url);
            
            // $api = new \Common\Extend\Api\ApiClient();
            // $api = $api->sms();
            // $api->mobile       = $userinfo['mobile'];  
            // $content = "{$info['name']}你好！你在西西钱包的借入款项已入账，到账金额{$info['payable']}元，还款期为{$date}，还款金额为{$info['money']}元，客服热线0771-5717965";
            // $api->content      = $content;
            // $api->Send('get')->data();
            $trl = true;
        }else{
            $data = ['status'=>$status];
            if($status==3){ //不通过
                D('Notice')->weixin(8,$info['uid'],['money'=>$info['money'],'day'=>$info['day'],'date'=>date('Y-m-d H:i:s',$info['create_time']),'content'=>'综合评分不足']);
                // $bank=D('BankCard')->where(array('uid='.$info['uid'],'card_number'=>$info['bank_card']))->find();
                // $url='http://sh2.ipyy.com/smsJson.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！很抱歉的通知您、您申请的'.$info['money'].'元借款未通过审核，感谢您的使用！&sendTime=&extno=';
                // $this->send_post($url);
            }elseif($status==4){ //通过(待打款)
                D('Notice')->weixin(7,$info['uid'],['name'=>$info['name'],'money'=>$info['money']]);
                $bank=D('BankCard')->where(array('uid='.$info['uid']))->find();
                $wh=substr($bank['card_number'],-4);
                $url='http://sh2.ipyy.com/smsJson.aspx?action=send&userid=&account=jkwl362&password=ndp987&mobile='.$bank['mobile'].'&content=【西西钱包】'.$bank['name'].'您好！很开心的通知您、您申请的借款'.$info['money'].'元已通过审核，将在2小时内由资金方汇入您的('.$wh.')账户,客服热线0771-5717965&sendTime=&extno=';
                $this->send_post($url);
                // $api = new \Common\Extend\Api\ApiClient();
                // $api = $api->sms();
                // $api->mobile       = M('Member')->where("uid={$info['uid']}")->getField('mobile');
                // $content = "{$info['name']}你好！很开心的通知你、你的借款{$info['money']}元已通过审核，将在2小时内入账，请留意预留银行账户,客服热线0771-5717965";
                // $api->content      = $content;
                // $api->Send('get')->data();
                $trl = true;
            }
        }
        $list = M('Loan')->where($map)->save($data);
        if(!empty($list)){
            $data = [
                'uid'           =>$uid,
                'loan_id'       =>$info['id'],
                'content'       =>$content,
                'create_time'   =>time(),
                'status'        =>$status,
            ];
            $trl = M('LoanLog')->add($data);
            if($trl) return ['status'=>true,'info'=>'操作成功'];else return ['status'=>false,'info'=>'操作失败'];
        }else{
            return ['status'=>false,'info'=>'操作失败'];
        }
    }



     // /**
    //  * 发送post请求
    //  * @param string $url 请求地址
    //  * @param array $post_data post键值对数据
    //  * @return string
    //  */
    function send_post($url) {
        $post_data = array(
          'username' => 'jkwl362',
          'password' => 'ndp987'
        );
     
      $postdata = http_build_query($post_data);
      $options = array(
        'http' => array(
          'method' => 'POST',
          'header' => 'Content-type:application/x-www-form-urlencoded',
          'content' => $postdata,
          'timeout' => 60 // 超时时间（单位:s）
        )
      );
      $context = stream_context_create($options);
      $result = file_get_contents($url, false, $context);
    } 

}
